package com.liang.servlet.provider;

import com.alibaba.fastjson.JSONArray;
import com.liang.pojo.Provider;
import com.liang.pojo.User;
import com.liang.service.Provider.ProviderServiceImpl;
import com.liang.util.Constant;
import com.liang.util.PageSupport;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class ProviderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")){
            getProviderList(req,resp);
        } else if (method.equals("view")||method.equals("modify")) {
            getProviderDetail(req,resp,method);
        } else if (method.equals("modifyexe")) {
            updateProviderInfo(req,resp);
        } else if (method.equals("add")) {
            insertProviderInfo(req,resp);
        } else if (method.equals("delprovider")) {
            deleteProvider(req,resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

//    获取供应商分页列表
    public static void getProviderList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryProCode = req.getParameter("queryProCode");
        String queryProName = req.getParameter("queryProName");
        String pageIndex = req.getParameter("pageIndex");
        Integer count = 0;
        int pageNo=1;
        int pageSize=8;

        ProviderServiceImpl providerService = new ProviderServiceImpl();
        count= providerService.getCount(queryProCode, queryProName);
        if (!StringUtils.isNullOrEmpty(pageIndex)){
            pageNo = Integer.parseInt(pageIndex);
        }
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(count);
        pageSupport.setTotalPageCountByRs();
        int MaxPageNo = pageSupport.getTotalPageCount();
        if(pageNo<1){
            pageNo=1;
        }else if (pageNo > MaxPageNo) {
            pageNo = MaxPageNo;
        }

        List<Provider> providerList = providerService.getProviderList(queryProCode, queryProName, pageNo, pageSize);



        req.setAttribute("queryProCode",queryProCode);
        req.setAttribute("queryProName",queryProName);
        req.setAttribute("totalCount",count);
        req.setAttribute("currentPageNo",pageNo);
        req.setAttribute("totalPageCount", MaxPageNo);
        req.setAttribute("providerList", providerList);

        req.getRequestDispatcher("providerlist.jsp").forward(req,resp);
    }

    public static void getProviderDetail(HttpServletRequest req, HttpServletResponse resp,String method) throws IOException, ServletException {
        String proid = req.getParameter("proid");
        Integer id = 0;
        if(!StringUtils.isNullOrEmpty(proid)){
            id = Integer.valueOf(proid);
        }

        if(id>0){
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            Provider providerView = providerService.getProviderView(id);

            req.setAttribute("provider",providerView);
            if(method.equals("view")){
//                详情页
                req.getRequestDispatcher("providerview.jsp").forward(req,resp);
            }else {
//                编辑页
                req.getRequestDispatcher("providermodify.jsp").forward(req,resp);
            }


        }else {
            req.getRequestDispatcher("providerlist.jsp").forward(req,resp);
        }
    }

//修改供应商信息
    public static void updateProviderInfo(HttpServletRequest req, HttpServletResponse resp){
        String uid = req.getParameter("uid");
        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String phone = req.getParameter("proPhone");
        String address = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        Integer id = 0;
        Boolean flag = false;
        if(!StringUtils.isNullOrEmpty(uid)){
            id = Integer.valueOf(uid);
        }

        try {
            HttpSession session = req.getSession();
            Object userSession = session.getAttribute(Constant.USER_SESSION);
            User user = (User) userSession;
            Integer modifyBy = user.getId();
            Date modifyDate = new Date();
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            flag = providerService.updateProvider(id, proCode, proName, proContact, phone, address, proFax, proDesc,modifyBy,modifyDate);
            if (flag){
                resp.sendRedirect("provider.do?method=query");
            }else {
                req.setAttribute(Constant.Message,"提交失败！");
                req.getRequestDispatcher("provider.do?method=modify&proid="+uid).forward(req,resp);
            }
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //添加供应商
    public static void insertProviderInfo(HttpServletRequest req, HttpServletResponse resp){

        String proCode = req.getParameter("proCode");
        String proName = req.getParameter("proName");
        String proContact = req.getParameter("proContact");
        String phone = req.getParameter("proPhone");
        String address = req.getParameter("proAddress");
        String proFax = req.getParameter("proFax");
        String proDesc = req.getParameter("proDesc");
        Boolean flag = false;


        try {
            HttpSession session = req.getSession();
            Object userSession = session.getAttribute(Constant.USER_SESSION);
            User user = (User) userSession;
            Integer createdBy = user.getId();
            Date creationDate = new Date();
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            //            根据供应商编码保持数据唯一性
            Provider provideOfProCode = providerService.getProvideOfProCode(proCode);

            if (provideOfProCode==null){
//                不存在即添加供应商
                flag = providerService.insertProvider( proCode, proName, proContact, phone, address, proFax, proDesc,createdBy, creationDate);
                if (flag){
                    resp.sendRedirect("provider.do?method=query");
                }  else {
                    req.setAttribute(Constant.Message,"提交失败！");
                    req.getRequestDispatcher("provideradd.jsp").forward(req,resp);
                }
            }else {
                req.setAttribute(Constant.Message,"供应商编码已存在，请重新输入");
                req.getRequestDispatcher("provideradd.jsp").forward(req,resp);
            }

        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void deleteProvider(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String proid = req.getParameter("proid");
        HashMap<Object, Object> resultMap = new HashMap<>();
        Integer id = 0;
        if(!StringUtils.isNullOrEmpty(proid)){
            id = Integer.parseInt(proid);
        }

        if(id>0){
            ProviderServiceImpl providerService = new ProviderServiceImpl();
            Provider view = providerService.getProviderView(id);
            if(view == null){
                resultMap.put("delResult","notexist");
            }else {
                Boolean flag = providerService.deleteProvider(id);
                if(flag){
                    resultMap.put("delResult","true");
                }else {
                    resultMap.put("delResult","false");
                }
            }


        }else {
            resultMap.put("delResult","false");
        }

        PrintWriter writer = resp.getWriter();
        writer.println(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }



}
